<template>

  <div v-if="cartList.length>0">
  <el-row class="title">
    <el-col :span="2">
      <el-checkbox
          label="全选"
          v-model="checkAllState"
          :indeterminate="halfState"
          @change="checkAllOrNone"
      /></el-col>
    <el-col :span="11">商品</el-col>
    <el-col :span="2">单价</el-col>
    <el-col :span="6">数量</el-col>
    <el-col :span="2">小计</el-col>
    <el-col :span="1">操作</el-col>
  </el-row>
  <el-row v-for="(cart, index) in cartList" :key="index" class="cartItem">
    <el-col :span="2">
      <el-checkbox  v-model="cart.checkState" @change="changeState"/>
    </el-col>
    <el-col :span="2">
      <el-image
          :src="`${SERVER_ADDR}/goods/pic/${cart.goods.picList[0].url}`"
      style="height: 40px; width: 40px"
          fit="contain"
      />
    </el-col>
    <el-col :span="5">{{cart.goods.name}}</el-col>
    <el-col :span="4">{{cart.goods.color}}-{{cart.goods.version}}</el-col>
    <el-col :span="2">{{cart.goods.price}}</el-col>
    <el-col :span="6">
      <el-input-number
          v-model="cart.count"
          :min="1"
          size="small"
          @change="updateCount(cart)"/>
    </el-col>
    <el-col :span="2">{{cart.goods.price * cart.count}}</el-col>
    <el-col :span="1">
      <el-button type="danger" :icon="Delete" circle
      @click="deleteById(cart.id)"
      />
    </el-col>
  </el-row>

  <el-row class="cartFooter">
    <el-col :span="2"><el-checkbox
    label="全选"
    v-model="checkAllState"
    :indeterminate="halfState"
    @change="checkAllOrNone"
    /></el-col>
    <el-col :span="3">
      <el-link :underline="false" @click="deleteChecked">
      删除选中的商品
      </el-link>

    </el-col>
    <el-col :span="11">
      <el-link :underline="false" @click="deleteAll">
      清空购物车
      </el-link>
    </el-col>
    <el-col :span="3">已选择{{checkedCount}}件商品</el-col>
    <el-col :span="3">总价：￥{{total}}</el-col>
    <el-col :span="2" ><el-button type="danger" @click="toCrateOrderView">结算</el-button></el-col>
  </el-row>
  </div>

  <div v-else class="none">
    购物车空空，快去购物吧<RouterLink to="/user/index" style="font-size: 20px;color:dodgerblue">去购物>></RouterLink>


  </div>

</template>

<script setup>
import {ref} from "vue";
import cartApi from "@/api/cartApi.js";
import {ElMessage} from "element-plus";
import {Delete} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";

const router=useRouter();
//服务器地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
//获取当前用户所有的购物车信息
const cartList= ref([]);
//全选按钮是否被选中
const checkAllState=ref(false);
//没有全选的状态
const halfState=ref(false);
//选中商品的总数量
const checkedCount = ref(0);
//选中商品的总金额
const total = ref(0);
function toCrateOrderView(){
  let cartIds=[];
  cartList.value.forEach(cart =>{
    if(cart.checkState){
      cartIds.push(cart.id)
    }
  });
  if(cartIds.length==0){
    ElMessage.warning("你还没选择商品无法结算")
  return;
  }
  router.push({
  path:"/user/createOrder" ,
   query:{
    cartIds
   }
  })
}

//清空购物车
function  deleteAll(){
  let ids=[];
  cartList.value.forEach(cart => {
    ids.push(cart.id);
  });
  if(ids.length ===0){
    ElMessage.warning("错误操作，购物车中没有商品");
    return;
  }
  //调用后端方法批量删除
  cartApi.deleteByIds(ids)
      .then(resp => {
        if (resp.code === 10000){
          ElMessage.success(resp.msg);
          cartList.value=cartList.value.filter(cart =>!cart.checkState);
          changeState();
          selectCartList();
        }
        else {
          ElMessage.error(resp.msg)
        }
      })

}
//批量删除
function  deleteChecked(){
  let ids=[];
  cartList.value.forEach(cart => {
    if(cart.checkState){
      ids.push(cart.id);
    }
  });
  if(ids.length === 0){
    ElMessage.warning("没有选中购物车中的商品，无法删除");
    return;
  }
  //调用后端方法批量删除
  cartApi.deleteByIds(ids)
      .then(resp => {
        if (resp.code==10000){
          ElMessage.success(resp.msg);
          selectCartList();
          changeState();
        }
        else {
          ElMessage.error(resp.msg)
        }
      })
}

//查询当前用户所有的购物车信息
function selectCartList(){
  cartApi.selectCartList()
      .then(resp =>{
        cartList.value=resp.data;
      })

}
//根据id删除
function deleteById(id){
  cartApi.delete(id)
      .then(resp =>{
    if (resp.code==10000){
      ElMessage.success(resp.msg)
      //将被删除的cartList中清除
      cartList.value=cartList.value.filter(cart=>cart.id != id);
      //设置全选按钮的状态
      changeState();
      getCountAndTotal();
    }else {
      ElMessage.error(resp.msg)
    }
  });
}
//
function updateCount(cart){
  const cartInfo={
    id:cart.id,
    count:cart.count
  };
  cartApi.update(cartInfo)
      .then(resp=>{
        if (resp.code === 10000){
          //让购物车中的商品数量和数据库中保持一致
          cartApi.selectById(cartInfo.id)
              .then(resp=>{
                cartList.value.forEach(cart=>{
                 if(cart.id == cartInfo.id){
                   cart.count=resp.data.count;
                 }
                });
                getCountAndTotal();
              })
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//全选全不选
function checkAllOrNone(){
  //让购物车中的全部商品的选择按钮与全选按钮保持一致
  cartList.value.forEach(cart =>{
    cart.checkState=checkAllState.value;
  });
  getCountAndTotal();
}
//购物车中的选择按钮发生变化调用的函数
function changeState(){
  /*
  *1.如果所有的选择按钮被选中 ，全选的按钮被选中
  * 2.如果所有的选择按钮部分被选中，全选按钮不选中
  * */
  let count =0;
  cartList.value.forEach(cart =>{
    if(cart.checkState){
      count++;
    }
  });
  if(count === cartList.value.length){
    checkAllState.value=true;
    halfState.value=false;
  }else if(count===0){
    checkAllState.value=false;
    halfState.value = false;
  }else {
    halfState.value=true;
  }
  getCountAndTotal();
}
//计算所选中的商品的总金额
function getCountAndTotal(){
  checkedCount.value=0;
  total.value=0;
  cartList.value.forEach(cart=>{
    if (cart.checkState){
      checkedCount.value += cart.count;
      total.value +=cart.goods.price * cart.count;
    }
  });
}


selectCartList();

</script>
<style scoped>
.none{
  font-size: 40px;
  text-align: center;
  height: 300px;
  line-height: 300px;
}

/* 全局样式重置 */
body, html, #app {
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

/* 标题栏样式 */
.title {
  background-color: #ff6800;
  color: white;
  margin-top: 10px;
  padding-left: 10px;
  text-align: left;
  font-weight: bold;
}

.title .el-col {
  border-right: 1px solid rgba(255, 255, 255, 0.3);
}

.title .el-col:last-child {
  border-right: none;
}

/* 购物车商品项样式 */
.cartItem {
  margin-top: 10px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.cartItem:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.cartItem .el-checkbox {
  margin-right: 15px;
}

.cartItem .el-image {
  display: inline-block;
  vertical-align: middle;
  border-radius: 4px;
}

.cartItem .el-col:nth-child(2) {
  width: 80px; /* 固定商品图片列宽度 */
}

.cartItem .el-col:nth-child(5),
.cartItem .el-col:nth-child(6),
.cartItem .el-col:nth-child(7) {
  text-align: center;
}

.cartItem .el-input-number {
  width: 100%;
  text-align: center;
  border-radius: 4px;
}

/* 购物车底部样式 */
.cartFooter {
  background-color: #ff6800;
  color: white;
  padding: 15px 0;
  text-align: right;
  font-size: 16px;
  border-radius: 8px;
  margin-top: 20px;
}

.cartFooter .el-col {
  border-left: 1px solid rgba(255, 255, 255, 0.3);
}

.cartFooter .el-col:first-child {
  border-left: none;
  padding-left: 20px;
}

.cartFooter .el-col:last-child {
  padding-right: 20px;
}

/* 复选框和按钮样式 */
.el-checkbox__inner {
  border-color: #ff6800;
  background-color: white;
}

.el-checkbox__inner:hover {
  border-color: #ff8033;
}

.el-checkbox__inner.is-checked {
  border-color: #ff6800;
  background-color: #ff6800;
}

.el-button.is-danger {
  background-color: #ff6800;
  border-color: #ff6800;
  color: white;
}

.el-button.is-danger:hover {
  background-color: #e65c00;
  border-color: #e65c00;
}

/* 其他细节样式 */
.el-row {
  margin-bottom: 10px;
}

.el-input-number .el-input__inner {
  border-color: #dcdcdc;
  border-radius: 4px;
}

.el-input-number .el-input__inner:focus {
  border-color: #ff6800;
  outline: none;
}

</style>